//
//  NetWorkManager.m
//  DailyRecord
//
//  Created by Gin on 2022/3/27.
//

#import "NetWorkManager.h"
#import <AFNetworking/AFNetworking.h>

static AFHTTPSessionManager *manager = nil;

@implementation NetWorkManager

+ (void)initialize{
    manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
}

+ (AFHTTPRequestSerializer *)generaterequestSerializerWithType:(NetWorkManagerrequestSerializerType)requestSerializerType{
    AFHTTPRequestSerializer *serializer = nil;
    if (requestSerializerType == NetWorkManagerrequestSerializerTypeForm) {
        serializer = [AFHTTPRequestSerializer serializer];
    } else if (requestSerializerType == NetWorkManagerrequestSerializerTypeJson){
        serializer = [AFJSONRequestSerializer serializer];
    }
    return serializer;
}

+ (void)getWithURLString:(NSString *)URLString
              parameters:(id)parameters
                 headers:(NSDictionary *)headers
                 success:(RequestSuccessBlock)success
                 failure:(RequestFailBlock)failure {
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager GET:URLString parameters:parameters headers:headers progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(task, responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(task ,error);
        }
    }];
}

+ (void)postWithURLString:(NSString *)URLString
   requestSerializerType:(NetWorkManagerrequestSerializerType)requestSerializerType
              parameters:(id)parameters
                 headers:(NSDictionary *)headers
                 success:(RequestSuccessBlock)success
                 failure:(RequestFailBlock)failure {
    manager.requestSerializer = [self generaterequestSerializerWithType:requestSerializerType];
    [manager POST:URLString parameters:parameters headers:headers progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(task, responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(task ,error);
        }
    }];
}

+ (void)postWithURLString:(NSString *)URLString
               parameters:(id)parameters
                  headers:(NSDictionary *)headers
                  success:(RequestSuccessBlock)success
                  failure:(RequestFailBlock)failure {
    [self postWithURLString:parameters requestSerializerType:NetWorkManagerrequestSerializerTypeForm parameters:parameters headers:headers success:success failure:failure];
}

@end
